package com.jiepos.mpos.core.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Vector;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
 

/**
* collection集合处理工具类
* @ClassName: CollectionUtil
* @Description:  集合工具类
* @author: 娄伟峰
* 创建时间:2012-5-11 上午10:46:13
 */
public class CollectionUtil {
	
	private static final Logger log = LoggerFactory.getLogger(CollectionUtil.class);

 
	
	/**
	 * 去除list中重复数据
	 * @param list
	 * @return
	 */
	public   static   List  removeDuplicate(List list)  {   
	    HashSet h  =   new  HashSet(list);   
	    list.clear();   
	    list.addAll(h);   
	    return list;   
	}   

//	/**
//	 * 将一个结果集转化为json数据结构
//	 * 
//	 * @param source
//	 * @return
//	 */
//	public static String list2Json(List<Serializable> source) {
//		try {
//			if (null == source || source.isEmpty()) {
//				return null;
//			}
//			StringBuffer json = null;
//			if (source.get(0) instanceof Map) {
//				json = new StringBuffer(JSONArray.fromObject(source).toString());
//			} else {
//				json = new StringBuffer(StringPool.CHARACTER_MIDDLE_LEFT);
//				for (int i = 0; i < source.size(); i++) {
//					Object item = source.get(i);
//					if (item instanceof Serializable) {
//						Class clazz = item.getClass();
//						if (ClassUtils.hasMethod(clazz,
//								StringPool.REFLECTION_METHOD_JSON, null)) {
//							String temp = ReflectionUtils.invokeMethod(
//									ClassUtils.getMethodIfAvailable(clazz,
//											StringPool.REFLECTION_METHOD_JSON,
//											null), item).toString();
//							json.append(temp);
//						} else {
//							json.append(JSONArray.fromObject(item).toString());
//						}
//					} else if (item instanceof Map) {
//						json.append(JSONArray.fromObject(item).toString());
//					}
//					json.append(StringPool.CHARACTER_COMMA);
//				}
//				json.deleteCharAt(json.lastIndexOf(StringPool.CHARACTER_COMMA));
//				json.append(StringPool.CHARACTER_MIDDLE_RIGHT);
//			}
//			return json.toString();
//		} catch (Exception e) {
//			return null;
//		}
//	}
	
	/**
	 * 将存放String的列表转化为","分隔的字符串
	 * @param list
	 * @return
	 */
	public static String list2String(List list) {
		StringBuffer sb = new StringBuffer();
		
		for (Object obj: list) {
			sb.append(",").append(String.valueOf(obj));
		}
		
		return sb.toString().replaceFirst(",", "");
	}

	 

	/**
	 * 将数据库值列表转为表格显示的xml
	 * @param list
	 * @return
	 */
	public static String list2GridXml(List list) {
		if (list == null || list.size() == 0) {
			return "";
		}
		String rs = "";

		Document document = DocumentHelper.createDocument();
		Element rowsElement = document.addElement("rows");
		for (Object obj : list) {
			Object[] objs = (Object[]) obj;
			Element rowElement = rowsElement.addElement("row");
			rowElement.addAttribute("id", (String) objs[0]);
				
			for (int i = 0; i < objs.length; i++) {
				Element cellElement = rowElement.addElement("cell");
				if (i == 0) {
					objs[i] = "0";
				}

				if(objs[i] != null && objs[i] != "" && objs[i] != "null"){
					cellElement.addCDATA((String) objs[i]);
				}
				

		//		cellElement.addText(StringUtil.convert((String) objs[i]));

			}
		}
		rs = document.asXML();

		rs = rs.replace("\r\n", "");
		rs = rs.replace("\r", "");
		rs = rs.replace("\n", "");
		return rs;
	}
	
	/**
	 * list 转换为json
	 * 每行数据为 : [id:1, text:市政府, url:/organization.do?dealMethod=, leaf:true, ]
	 * 第1列：id
	 * 第2列：显示的文本
	 * 第3列：点击后链接的地址
	 * 第4列：是否是叶子节点
	 * 第5列：是否带checkbox  
	 * @param list
	 * @param attributeNames 属性名 如 id,text,leaf ..., 至少包括 id,text,url,leaf 四项
	 * @return
	 */
	public static String list2Json(List<Object[]> list, String[] attributeNames, boolean checkbox) {
		String json = "";
		StringBuffer sb = new StringBuffer();
		if (CollectionUtil.isEmpty(list) || CollectionUtil.isEmpty(attributeNames)) {
			return json;
		}
		if (attributeNames.length < 4) {
			throw new RuntimeException("build json error : num of attributeNames is not enough.");
		}
		sb.append("[");
		
		try {
			for (Object[] row : list) {
				StringBuffer buf = new StringBuffer();
				for (int i = 0; i < row.length; i++) {
					if (row.length < 4) {
						throw new RuntimeException("Build tree json error:row's length not enough in the list.");
					}
					if (row[i] != null && !StringUtils.isEmpty(String.valueOf(row[i]))) {
						if (row[i] instanceof Boolean) {
							if ("checked".equals(attributeNames[i])){
								if (checkbox) {
									buf.append("," + attributeNames[i] + ":" + row[i] + "");
								} else {
									continue;
								}
							} else {
								buf.append("," + attributeNames[i] + ":" + row[i] + "");
							}
						} else if ("url".equals(attributeNames[i])) {
							buf.append("," + attributeNames[i] + ":'" + row[i] + "&" + getUrlSuffixRandom() + "'");
						} else {
							buf.append("," + attributeNames[i] + ":'" + row[i] + "'");
						}
					}
				}
				sb.append(",{" + buf.toString().replaceFirst(",", "") + "}");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.debug("build list 2 json error:", e);
		}
		sb.append("]");
		
		if (sb.length() == 2) {
			return "";
		}
		return sb.toString().replaceAll(",,", ",").replaceFirst("\\[,\\{", "\\[\\{");
	}
	/**
	 * 获取url后缀的随机尾数
	 * 如：...ac.jsp   -> ...ac.jsp...&rs=1092
	 * @return rs=1091，不带"&"
	 */
	public static String getUrlSuffixRandom() {
		return new StringBuffer().append("rs=").append(new Random().nextInt(10000)).toString();
	}

	
	
	/**
	 * list 转换为xml
	 * 每行数据为 : [id:1, pid:2, text:市政府, url:/organization.do?dealMethod=, leaf:true, ]
	 * 第1列：id
	 * 第2列：显示的文本
	 * 第3列：点击后链接的地址
	 * 第4列：是否是叶子节点
	 * 第5列：是否带checkbox  
	 * @param list
	 * @param attributeNames 属性名 如 id,text,leaf ..., 至少包括 id,text,url,leaf 四项
	 * @return
	 */
	public static String list2TreeXml(List<Object[]> list, String[] attributeNames, boolean checkbox) {
		StringBuffer sb = new StringBuffer();
		if (CollectionUtil.isEmpty(list) || CollectionUtil.isEmpty(attributeNames)) {
			return "";
		}
		if (attributeNames.length < 4) {
			throw new RuntimeException("build json error : num of attributeNames is not enough.");
		}
		
		//节点问文本索引值
		int textIndex = 0;
		
		for (int i = 0; i < attributeNames.length; i++) {
			if ("text".equals(String.valueOf(attributeNames[i]))) {
				textIndex = i;
				break;
			}
		}
		
		try {
			sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			sb.append("<nodes>");
			for (Object[] row : list) {
				sb.append("<node");
				for (int i = 0; i < row.length; i++) {
					if (row.length < 4) {
						throw new RuntimeException("Build tree json error:row's length not enough in the list.");
					}
					if (i != textIndex) {
						sb.append(" " + attributeNames[i] + "='" + row[i] + "'");
					}
				}
				sb.append(">").append(row[textIndex]).append("</node>");
			}
			sb.append("</nodes>");
		} catch (Exception e) {
			e.printStackTrace();
			log.debug("build list 2 treexml error:", e);
		}
		
		return sb.toString();
	}
	
	public static String array2GridXml(String[][] array) {
		if (array == null || array.length == 0) {
			return "";
		}
		
		String rs = "";
		try {
			// 构造表格xml
			Document document = DocumentHelper.createDocument();
			Element rowsElement = document.addElement("rows");
			for (String[] row : array) {
				Element rowElement = rowsElement.addElement("row");
				rowElement.addAttribute("id", row[0]);
				
				for (int i = 1; i < row.length; i++) {
					Element cellElement = rowElement.addElement("cell");
					cellElement.addText(row[i]);
				}
			}
			
			rs = document.asXML();
		} catch (Exception e) {
			log.debug("build array 2 grid xml error:", e);
		}
		
		return rs;
	}
	
	public static void haha(String dd, String cc, List... obj) {
	 
		List[] ff = obj;
		for (List ll : obj) {
			
		}
	 
	}
	
	public static String buildGrid(/*, List headList*/ List dataList, String htmlId) {
		StringBuffer sb = new StringBuffer();
		sb.append("<script type=\"text/javascript\">\n");
		sb.append("var mygrid;\n");
		sb.append("mygrid = new dhtmlXGridObject('"+htmlId+"');\n");
		sb.append("mygrid.setImagePath(\"../imgs/\");\n");
		sb.append("mygrid.setHeader(\"Column A,Column B\");\n");
		sb.append("mygrid.setInitWidths(\"100,*\");\n");
		sb.append("mygrid.setColAlign(\"right,right\");\n");
		sb.append("mygrid.setColTypes(\"ed,ed\");\n");
		sb.append("mygrid.enableLightMouseNavigation(true);\n");
		sb.append("mygrid.enableDragAndDrop(true);;\n");
		sb.append("mygrid.setColSorting(\"str,str\");");
		sb.append("mygrid.setSkin(\"light\");\n");
		sb.append("mygrid.init();\n");
		sb.append("mygrid.parse('"+list2GridXml(dataList)+"');\n");
		sb.append("</script>\n");
		
		return sb.toString();
	}

	/**
	 * 取得一个map对应的key值的value
	 * 
	 * @param map
	 * @param key
	 * @return 1、如果不存在key,那么返回null 2、如果布在key,但value不存在,则返回null
	 *         3、如果存在key,同时存在value 则返回object
	 */
	public static Object getMapValueByKey(Map map, Object key) {
		if (null == key) {
			return null;
		}
		if (!map.containsKey(key)) {
			return null;
		} else {
			if (null == map.get(key)) {
				return null;
			} else {
				return map.get(key);
			}
		}
	}
	
	/**
	 * 判断list是否为空
	 * @param list
	 * @return 为空（null 或 size == 0）返回true, 不为空返回false
	 */
	public static boolean isEmpty(List<?> list) {
		return list == null || list.size() == 0;
	}
	
	/**
	 * 判断map是否为空
	 * @param map
	 * @return 为空（null 或 size == 0）返回true, 不为空返回false
	 */
	public static boolean isEmpty(Map<?,?> map) {
		return map == null || map.size() == 0;
	}
	
	/**
	 * 判断数组是否为空
	 * @param array
	 * @return 为空（null 或 length == 0）返回true, 不为空返回false
	 */
	public static boolean isEmpty(Object[] array) {
		return array == null || array.length == 0;
	}
	
	/**
	 * list转换工具
	 * @param list
	 * @return 
	 * 		如果list为null, 返回一个空的list，否则返回原来的list	
	 */
	public static List convert(List list) {
		if (list == null || list.size() == 0) {
			if (list instanceof ArrayList) {
				list = new ArrayList();
			} else if (list instanceof Vector) {
				list = new Vector();
			} else {
				list = new ArrayList();
			}
		}
		return list;
	}
	
	/**
	 * map转换工具
	 * @param map
	 * @return 
	 * 		如果map为null, 返回一个空的map，否则返回原来的map
	 */
	public static Map convert(Map map) {
		if (map == null || map.size() == 0) {
			if (map instanceof HashMap) {
				map = new HashMap();
			} else if (map instanceof Hashtable) {
				map = new Hashtable();
			} else {
				map = new HashMap();
			}
		}
		return map;
	}
	
	public static void main(String[] args) {
		List list = new ArrayList();
		Map map = new HashMap();
		Object[] objs = new Object[]{"1","212", "哈哈",null, true};
		Object[] objs2 = new Object[]{"2","121", null, "hhh", true};
		list.add(objs);
		list.add(objs2);
		System.out.println(list2TreeXml(list, new String[]{"id", "pid", "text", "url", "checked"}, false));
		
		
	}
	
}
